<template>
    <div class="c-main">
        <div class="inp">
            <el-autocomplete
                style="flex: 1"
                v-model="address"
                :fetch-suggestions="querySearch"
                placeholder="请输入详细地址"
                :trigger-on-focus="false" />
            <el-button class="ml-20" type="primary" icon="Search" @click="getLocation">
                搜索
            </el-button>
        </div>
        <div class="mt-20 showinp">
            <el-input v-model="mapInfo.address" placeholder="请选择地点" disabled />
        </div>
        <div class="mapbox mt-20">
            <div class="map" id="tx_map_d"></div>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { getAddress, getSuggestion, getgeocoder } from '@/api/map';
import { nextTick, onMounted, ref, reactive } from 'vue';
interface mapT {
    address: string;
    lat: string;
    lng: string;
}
let address = ref<string>('');
const mapInfo = reactive<mapT>({
    address: '',
    lat: '',
    lng: '',
});
const keys = '';

const dataMap = reactive({
    map: '',
    markerLayer: '',
    latitude: '39.984120',
    lngitude: '116.307484',
});
const TMap = (window as any).TMap;

onMounted(() => {
    // getLocation();
    nextTick(() => {
        initMap();
    });
});
const initMap = () => {
    let center = new TMap.LatLng(dataMap.latitude, dataMap.lngitude);
    dataMap.map = new TMap.Map('tx_map_d', {
        center: center,
        zoom: 11,
        viewMode: '2D',
    });
    // 绑定地图点击获取地理位置事件
    (dataMap.map as any).on('click', clickHandler);
    // 标记地图
    markerLayer();
};
// 搜索
const getLocation = async () => {
    try {
        let params = {
            key: keys, // 填申请到的腾讯key
            address: address.value,
        };
        let { result } = await getAddress(params);
        if (result) {
            dataMap.latitude = result.location.lat;
            dataMap.lngitude = result.location.lng;
            (dataMap.map as any).setCenter(new TMap.LatLng(dataMap.latitude, dataMap.lngitude));
            mapInfo.address = address.value;
            mapInfo.lat = dataMap.latitude;
            mapInfo.lng = dataMap.lngitude;
            reloadMap();
        }
    } catch (e) {
        console.log(e);
    }
};
// 点击获取经纬度
const clickHandler = (evt: any) => {
    dataMap.latitude = evt.latLng.getLat().toFixed(6);
    dataMap.lngitude = evt.latLng.getLng().toFixed(6);
    (dataMap.map as any).setCenter(new TMap.LatLng(dataMap.latitude, dataMap.lngitude));
    reloadMap();
    AddressByll();
};
// 重载地图
const reloadMap = () => {
    // (document.getElementById('tx_map_d') as any).innerHTML = '';
    // dataMap.markerLayer = '';
    // let center = new TMap.LatLng(dataMap.latitude, dataMap.lngitude);
    // dataMap.map = new TMap.Map('tx_map_d', {
    //     center: center, //设置地图中心点坐标
    //     viewMode: '2D',
    // });
    if (dataMap.markerLayer) {
        (dataMap.markerLayer as any).setMap(null);
    }

    markerLayer();
};
//标记地图
const markerLayer = () => {
    dataMap.markerLayer = new TMap.MultiMarker({
        map: dataMap.map, //指定地图容器
        //样式定义
        styles: {
            //创建一个styleId为"myStyle"的样式（styles的子属性名即为styleId）
            myStyle: new TMap.MarkerStyle({
                width: 25, // 点标记样式宽度（像素）
                height: 35, // 点标记样式高度（像素）
                // "src": '../../assets/logo.png',  //图片路径
                background: 'pink',
                //焦点在图片中的像素位置，一般大头针类似形式的图片以针尖位置做为焦点，圆形点以圆心位置为焦点
                anchor: { x: 16, y: 32 },
            }),
        },
        //点标记数据数组
        geometries: [
            {
                id: '1', //点标记唯一标识，后续如果有删除、修改位置等操作，都需要此id
                styleId: 'myStyle', //指定样式id
                position: new TMap.LatLng(dataMap.latitude, dataMap.lngitude), //点标记坐标位置
            },
        ],
    });
};
// 输入建议
const querySearch = async (queryString: string, cb: any) => {
    try {
        let params = {
            keyword: queryString,
            key: keys, // 填申请到的腾讯key
        };
        let { data } = await getSuggestion(params);

        const results = data.map((item: any) => {
            let obj = {
                value: item.address,
                address: item.address,
            };
            return obj;
        });
        cb(results);
    } catch (e) {
        console.log(e);
    }
};

// 经纬度获取地点
const AddressByll = async () => {
    try {
        let params = {
            location: dataMap.latitude + ',' + dataMap.lngitude,
            key: keys, // 填申请到的腾讯key
        };
        let { result } = await getgeocoder(params);
        mapInfo.address = result.address;
        mapInfo.lat = result?.location?.lat;
        mapInfo.lng = result?.location?.lng;
        address.value = '';
    } catch (e) {
        console.log(e);
    }
};
</script>

<style lang="scss" scoped>
.c-main {
    overflow: hidden;
    .inp {
        width: 650px;
        display: flex;
    }
    .showinp {
        width: 650px;
    }
    .mapbox {
        height: calc(100% - 104px);
        max-height: calc(100% - 104px);
        overflow: hidden;
        .map {
            width: 100%;
            height: 100%;
        }
    }
}
</style>
